package com.godme.gateway.filter;


import com.godme.gateway.service.LimitService;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@ServletComponentScan
@Order
public class LimitFilter implements Filter {

    @Resource
    private LimitService limitService;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String host = servletRequest.getRemoteAddr();
        if(!request.getRequestURI().startsWith("/api/user/register") || limitService.allowAccess(host)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/plain;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.addHeader("error", "您频繁进⾏注册，请求已被拒绝");
        response.flushBuffer();
        response.getWriter().close();
    }
}
